const adminServ = require('../services/adminService')
const { asyncHandler } = require('../routes/getSendResult')
const jwt = require('../routes/jwt')
const path = require('path')

exports.login = asyncHandler(async (req, res) => {
  const result = await adminServ.login(req.body.username, req.body.password)
  if (result) {
    let value = result.id
    //登录成功
    jwt.publish(res, undefined, { id: value })
  }
  // 用户不存在
  return result
})

exports.deleteAdmin = asyncHandler(async (req) => {
  return await adminServ.deleteAdmin(req.params.adminId)
})

// 获取用户信息
exports.getAdmin = asyncHandler(async (req) => {
  const result = jwt.verify(req)
  if (result) {
    const id = result.id
    return await adminServ.getAdmin(id)
  }
  return null
})

exports.getAdmins = asyncHandler(async () => {
  return await adminServ.getAdmins()
})

exports.addAdmin = asyncHandler(async (req) => {
  return await adminServ.addAdmin(req.body)
})

// 修改密码
exports.updateAdmin = asyncHandler(async (req) => {
  const result = jwt.verify(req)
  const id = result.id
  if (!id) {
    return null
  }
  return await adminServ.updateAdmin(id, req.body)
})
